import re
import os.path
import os
import sys
import zipfile
import sublime, sublime_plugin
import subprocess
import threading
import shutil

ROOT_PTAH = 'XTool'
def readPath(projectPath):
   with open(os.path.join(projectPath,'simulator\\win32\\src\\main.lua'), 'r',encoding='UTF-8') as f:
   	filestr = f.readlines()
   	pathlist = [] ;
   	for line in filestr:
   		#print(line)
		#filepath = re.search('^(?:\s*)'+r'cc\.FileUtils\:getInstance\(\)\:addSearchPath\(\"\.\.\/\.\.\/\.\.\/' + '(.*)' +r'\"\)',line)	
   		filepath = re.search('^(?:\s*)'+r'cc\.FileUtils\:getInstance\(\)\:addSearchPath\(\"' + '(.*)' +r'\"\)',line)	
   		if filepath:
   			pathlist.append(filepath.group(1))
   	return pathlist ;



	
def copyTree(orgSrcPath,desSrcPath,view):
	if not os.path.exists(desSrcPath):
		os.makedirs(desSrcPath)
	print("orgSrcPath",orgSrcPath);
	for x in os.listdir(orgSrcPath):
		tpath = os.path.join(orgSrcPath,x)
		dpath = os.path.join(desSrcPath,x)
		#print("load file",dpath)
		print("load file",x)
		view.window().status_message("load file->"+x)
		if os.path.isdir(tpath):
			if not os.path.exists(dpath):
				os.makedirs(dpath)
			copyTree(tpath,dpath,view)
		else:
			shutil.copyfile(tpath,dpath)

def copySimulator(projectPath,view):
	copyTree(os.path.join(projectPath,'simulator/win32/'),os.path.join(projectPath,"win32pac/"),view)			

def copyPathRes(plist,projectPath,view):
	desPath = os.path.join(projectPath,'win32pac/src')
	rootPath,_= os.path.split(projectPath); 
	for path in plist:
		resPath = os.path.join(rootPath,path)
		#print("resPath",resPath)
		#print("desPath",desPath)
		copyTree(resPath ,desPath,view)
	

def zip_dir(dirname,zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        #print arcname
        zf.write(tar,arcname)
    zf.close()

def change_real_dir(paths,projectPath):
	basePath = os.path.join(projectPath,'simulator/win32/') ;
	list = []
	for path in paths:
		group = path.split('../')
		print(group)
		deep = len(group) - 1;
		desPath = group[deep]
		rootPath = basePath;
		while deep>=0:
			rootPath,_ = os.path.split(rootPath)
			deep = deep -1 
		#print("rootPath",rootPath)
		#print("desPath",desPath)
		#print("desddddd",os.path.join(rootPath,desPath))
		list.append(os.path.join(rootPath,desPath))
	return list

def removeIgnoreFile(projectPath):
	desPath = os.path.join(projectPath,"win32pac/")
	ignorePaths = ['log','.x-studio365','.vscode','.idea'] 
	for file in ignorePaths:
		desResPath = os.path.join(desPath,file)
		if os.path.exists(desResPath):
			if os.path.isdir(desResPath):
				shutil.rmtree(desResPath)
			else:
				os.remove(desResPath)
	for file in os.listdir(desPath):
		tpath = os.path.join(desPath,file)
		if file.find('get_') == 0:
			os.remove(tpath)

def copyBat(projectPath):
	desPath = os.path.join(projectPath,"win32pac/A_点我点我.bat")
	root = os.path.join(sublime.packages_path(),ROOT_PTAH)
	filePath = os.path.join(root,"A_点我点我.bat")
	print("desPath->",desPath)
	print("filePath->",filePath)
	shutil.copyfile(filePath,desPath)

	
def pac(projectPath,view):
	paths = readPath(projectPath)
	#print(paths)
	#print("11111111")
	paths = change_real_dir(paths,projectPath)
	copySimulator(projectPath,view)
	removeIgnoreFile(projectPath)
	copyPathRes(paths,projectPath,view)
	copyBat(projectPath)
	orginPath = os.path.split(projectPath)
	print("orginPath",orginPath)
	view.window().status_message("正在打包,请等待..")
	zip_dir(os.path.join(projectPath,'win32pac'),os.path.join(orginPath[0],"simulator.zip"))
	view.window().status_message("打包完成！！！！")
	os.startfile(orginPath[0])
	if os.path.exists(os.path.join(projectPath,'win32pac')):
		if os.path.isdir(os.path.join(projectPath,'win32pac')):
			shutil.rmtree(os.path.join(projectPath,'win32pac'))
	#print(paths)
	#print(sys.path[0])

#打包zip
class pacsimulatorCommand(sublime_plugin.TextCommand):
	def run(self, edit,snum=0):
		globals()['terrySettings'] = sublime.load_settings('DefaultDoC.sublime-settings')
		projectPath = globals()['terrySettings'].get('desPath','')
		if projectPath:
			 _thread = threading.Thread(target=pac, args=(projectPath,self.view))
			 _thread.setDaemon(True)
			 _thread.start()#启动线程

